package com.openlogic.gateway.handler;


import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.handle.Result;

import com.openlogic.common.core.constants.HttpConstant;

/**
 * 请求结束处理
 * 出现异常情况
 * @Author: ajie
 * @CreateTime: 2024-07-29 11:23
 */
public class AfterHandler implements Handler {

    @Override
    public void handle(Context ctx) throws Throwable {
        Throwable errors = ctx.errors;
        if (errors != null) {
            ctx.setHandled(true);
            if (errors instanceof RuntimeException) {
                ctx.render(Result.failure(HttpConstant.HTTP_INTERNAL_ERROR, errors.getMessage()));
            } else if (errors instanceof IllegalStateException){
                String message = errors.getMessage();
                String str = "No service address found";
                if (message.contains(str)) {
                    ctx.render(Result.failure("请检查服务["+ message.substring(str.length() + 1) +"]是否启动！"));
                } else {
                    ctx.render(Result.failure(errors.getMessage()));
                }
            } else {
                 ctx.render(Result.failure(errors.getMessage()));
            }
        }
    }
}
